package server;

import pojo.MappedContext;
import pojo.MappedHost;
import pojo.MappedWrapper;
import pojo.Mapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 动态资源servlet请求
            HttpServlet httpServlet = null;
            // 此时的mapper中以及保存了对应的context实例以及根据uri对应的servlet实例
            List<MappedContext> mappedContexts = mapper.getMappedHost().getMappedContexts();
            String uri = request.getUrl();
            if("/favicon.ico".equals(uri)){
                return;
            }
            // /demo01 对应的MappedContext的name
            String context = "/" + uri.split("/")[1];
            // /lagou 对应的MappedWrapper中的name
            String servlet = "/" + uri.split("/")[2];
            for (int i = 0; i < mappedContexts.size(); i++) {
                MappedContext mappedContext = mappedContexts.get(i);
                String contextName = mappedContext.getName();
                // 判断是否是同一个context实例
                if (contextName.equals(context)){
                    // 是同一个context实例则获取该实例下所有的servlet
                    List<MappedWrapper> mappedWrappers = mappedContext.getMappedWrappers();
                    for (int j = 0; j < mappedWrappers.size(); j++) {
                        MappedWrapper mappedWrapper = mappedWrappers.get(j);
                        // 根据name获取对应的servlet实例
                        if (servlet.equals(mappedWrapper.getName())){
                            httpServlet = (HttpServlet) mappedWrapper.getObject();
                        }else{
                            // 如果没有获取到，继续下一次循环
                            continue;
                        }
                    }
                }else{
                    // 如果不是直接跳出该循环，继续下一次循环
                    continue;
                }

            }
            httpServlet.service(request, response);
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
